/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * @Title: FireUrl.java
 * @Package phoenics.apeak.simple.service
 * @Description
 * @author phoenics@126com
 * @date 2016-1-30 16:01:31
 * @version V1.0
 */
package phoenics.apeak.simple.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import phoenics.apeak.crawl.Bootstrap;
import phoenics.apeak.crawl.service.DocumentPublisher;
import phoenics.apeak.simple.entity.UrlInfo;
import phoenics.apeak.simple.store.UrlInfoDao;
// TODO: Auto-generated Javadoc

/**
 * The Class FireUrl.
 *
 * @Description The Class FireUrl.
 */
@Service
public class FireUrl implements Bootstrap {
	
	/** The url info dao. */
	@Autowired
	private UrlInfoDao urlInfoDao;
	
	/** The document publisher. */
	@Autowired
	DocumentPublisher documentPublisher;
	
	/** The goods mapper. */
	ObjectMapper goodsMapper = new ObjectMapper();
	
	/* (non-Javadoc)
	 * @see phoenics.apeak.crawl.Bootstrap#start(java.lang.String)
	 */
	@Override
	public void start(String params) {
		int i=0;
		while(!eventLoop()){
			i++;
			if(i>6){
				break;
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
		}    
	}

	/* (non-Javadoc)
	 * @see phoenics.apeak.crawl.Bootstrap#initializeCrawl(java.lang.String)
	 */
	@Override
	public void initializeCrawl(String params) {
		String categories_url = "http://www.shopstyle.com/api/v2/categories?fields=id,name,shortName,parentId,localizedId&pid=shopstyle";
		documentPublisher.publish(TakeCategoryTreee.class, categories_url);
	}
	
	/**
 * Event loop.
 *
 * @Description Event loop.
 */
	private boolean eventLoop(){
		List<UrlInfo>  urls=urlInfoDao.findAll();
		if(urls==null || urls.isEmpty()){
			return false;
		}
		 urls=null;
		 while(hasUrlInfo()){
			 nextLoop();
		 }
		System.out.println("all crawl was over.");
		return true;
	}
	
	private void nextLoop(){
		Query query = new Query();
		query.addCriteria(Criteria.where("timeout").gt(0));
		List<UrlInfo>  urlInfos=urlInfoDao.find(query);
		for(UrlInfo u:urlInfos){
			if(u.getTimeout()>6){
				continue;
			}
			if(u.getOffset()<u.getTotal()){
				updateUrlInfo(u.getId());
			}
		}
		
	}
	private void updateUrlInfo(String category) {
		Query query = new Query();
		query.addCriteria(Criteria.where("id").is(category));
		Update update = new Update();
		update.set("over", 0);
		urlInfoDao.updateFirst(query, update);
	}
	/**
 * Checks for url info.
 *
 * @return true, if successful
 * @Description Checks for url info.
 */
	private boolean hasUrlInfo(){
		Query query = new Query();
		query.addCriteria(Criteria.where("over").is(0));
		query.with(new Sort(Direction.ASC, "offset"));
		List<UrlInfo>  urls=urlInfoDao.find(query);
		if(urls.size()==0){
			return false;
		}
		for (UrlInfo nextUrlInfo : urlInfoDao.find(query)) {
			String url = String.format(ParseShopStyle.url_templ, nextUrlInfo.getId(), nextUrlInfo.getLimit(), nextUrlInfo.getOffset());
			ObjectNode param = goodsMapper.createObjectNode();
			param.put("category", nextUrlInfo.getId());
			param.put("offset", nextUrlInfo.getOffset());
			param.put("total", nextUrlInfo.getTotal());
			documentPublisher.publish(ParseShopStyle.class, url, param.toString());
			System.out.println(param.toString());
			try {
				Thread.sleep(700);
			} catch (InterruptedException e) {
			}
		}
		
		return true;
	}
}
